/*
 * @Author: your name
 * @Date: 2022-02-22 16:23:39
 * @LastEditTime: 2022-05-02 09:36:31
 * @LastEditors: Please set LastEditors
 * @Description: 文章模块相关接口
 * @FilePath: \blog_backStageSystem\blog_serve\Routes\article.js
 */
const express = require("express");
const path = require("path");
const db = require(path.join(__dirname, "../Model/model"));
const moment = require("moment");
const { response } = require("express");
const res = require("express/lib/response");
const article = express.Router();

/**
 * @description: 文章列表查询接口
 * @param {*} pageSize 分页器大小
 * @param {*} pageNum 分页页码
 * @return {*}
 */
article.get("/article/list", (req, res) => {
  const { pageSize = 1, pageNum = 10 } = req.query;
  const startIndex = (pageSize - 1) * pageNum;
  let querySql = `SELECT * from article_list Where 1=1 `;
  let constSql = `SELECT COUNT(*) as total from article_list Where 1=1 `;
  let { articleName, category, creationDate, articleId } = req.query;
  if (articleName) {
    querySql += ` and articleName like "%${articleName}%"`;
    constSql += ` and articleName like "%${articleName}%"`;
  }
  if (category) {
    querySql += ` and category like "%${category}%"`;
    constSql += ` and category like "%${category}%"`;
  }
  if (creationDate) {
    querySql += ` and creationDate BETWEEN "${creationDate} 00:00:00" AND "${creationDate} 23:59:59"`;
    constSql += ` and creationDate BETWEEN "${creationDate} 00:00:00" AND "${creationDate} 23:59:59"`;
  }
  if (articleId) {
    querySql += ` and articleId = "${articleId}"`;
    constSql += ` and articleId = "${articleId}"`;
  }
  querySql += `order by articleId desc LIMIT ${startIndex}, ${pageNum} `;
  db(querySql, (err, result) => {
    db(constSql, (err, count) => {
      const data = result.map((d) => {
        const baseContent = new Buffer(d.content, "base64").toString();
        return {
          ...d,
          content: baseContent,
        };
      });
      res.send({
        content: data,
        total: count[0].total,
      });
    });
  });
});
/**
 * @description: 文章列表删除接口
 * @param {*}
 * @return {*}
 */
article.delete("/article/list/delete", (req, res) => {
  const ids = req.body;
  const deleteSql = `delete from article_list where articleId in (${ids.toString()})`;
  ids.forEach(d=>{
    // addCount(d,-1)
    const querySql = `select * from article_list where articleId=${d}`;
    console.log(querySql);
    db(querySql, (err,category_ids) => {
      console.log(category_ids[0]);
      const ids = category_ids[0].categoryId.split(",");
      ids.forEach(id => {
        addCount(id,-1)
      })
    })
  })
  db(deleteSql, (err, result) => {
    if (result.affectedRows !== 0) {
    
      res.send({
        failed: false,
        message: "删除成功",
      });
    }
  });
});
function addCount(categoryId, count){
  // console.log("tpye", count);
    const catequerySql = `select * from article_category where category_id=${categoryId}`;
    console.log(catequerySql);
    db(catequerySql,(err,result) => {
      const updateSql = `update article_category set category_count = ${
        result[0].category_count + count
      } where category_id=${result[0].category_id}`;
      console.log(updateSql);
      db(updateSql, (err, updateResult) => {})
      if (result[0].parentId) {
        addCount(result[0].parentId, count)
      }
    })
   
  
 
}
/**
 * @description: 文章保存接口
 * @param {*}
 * @return {*}
 */
article.post("/article/list/save", (req, response) => {
  const {
    articleName,
    category,
    categoryId,
    description,
    content,
    userId,
    author,
    articleCover,
    articleId,
  } = req.body;
  // 富文本内容可能包含特殊符号，不能直接进行保存，需要先将内容进行base64编码
  const baseContent = new Buffer(content).toString("base64");
  let insertSql = `INSERT INTO article_list (
        articleName,
        category,
        categoryId,
        description,
        content,
        userId,
        author,
        articleCover,
        creationDate
      )
      VALUES(
          '${articleName}',
           '${category.toString()}',
           '${categoryId.toString()}',
           '${description}',
           '${baseContent}',
           '${userId}',
           '${author}',
           '${articleCover}',
           '${moment(new Date().getTime()).format("YYYY-MM-DD hh:mm:ss")}'
        )`;
  db(insertSql, (err, result) => {
    if (result.affectedRows !== 0) {
      categoryId.forEach((item) => {
        addCount(item,1)
      });
      response.send({
        failed: false,
        message: "发布成功",
        result: result,
      });
    }
  });
});
/**
 * @description: 文章内容更新接口
 * @param {*}
 * @return {*}
 */
article.put("/article/list/update", (req, response) => {
  const {
    articleName,
    category,
    categoryId,
    description,
    content,
    userId,
    author,
    articleCover,
    articleId,
  } = req.body;
  const baseContent = new Buffer(content).toString("base64");
  const updateSql = `update article_list set 
    articleName = '${articleName}',
    category = '${category}',
    categoryId = '${categoryId}',
    description = '${description}',
    content = '${baseContent}',
    description = '${description}',
    author = '${author}',
    articleCover = '${articleCover}'
  WHERE articleId = ${articleId}`;
  db(updateSql, (err, res) => {
    response.send({
      message: "修改成功",
      result: res,
    });
  });
});

function fetchParentData(id, array) {
  let querySql = `SELECT * from article_category Where category_Id= ${id}`;
  db(querySql, (err, result) => {
    result.map((d) => {
      if (d.isTopLevel === 0) {
        fetchParentData(d.parentId, array);
      } else {
        array.push(d);
      }
    });
    return array;
  });
}
/**
 * @description:  标签查询接口
 * @param {*}
 * @return {*}
 */
article.get("/article/category", (req, res) => {
  const { category_name } = req.query;
  let querySql = "SELECT * from article_category Where 1= 1";
  if (category_name) {
    querySql += ` and category_name like '%${category_name}%'`;
  }
  const data = [];
  db(querySql, (err, result) => {
    result.map((d) => {
      data.push(d);
      if (d.isTopLevel === 0) {
        const parentData = fetchParentData(d.parentId, data);
      }
    });
    res.send({
      content: result,
    });
  });
});
/**
 * @description: 文章标签保存
 * @param {*}
 * @return {*}
 */
article.post("/article/category/save", (req, res) => {
  const {
    isTopLevel,
    category_name,
    parentCategory,
    childrenValue,
    category_id,
  } = req.body;
  if (category_id) {
    let updateSql = `update article_category set  category_name = '${category_name}' where category_id=${category_id}`;
    return db(updateSql, (err, result) => {
      if (result.affectedRows === 1) {
        res.send({
          failed: false,
          message: "更新成功",
        });
      }
    });
  }
  let insetSql = `INSERT INTO article_category (category_name,isTopLevel, category_count) VALUES ("${category_name}", ${
    isTopLevel ? 1 : 0
  },0)`;

  if (!isTopLevel) {
    let insetSql = `INSERT INTO article_category (category_name,isTopLevel, category_count,parentId) VALUES ("${category_name}", 0,0, ${parentCategory})`;
    db(insetSql, (err, result) => {
      if (result.affectedRows === 1) {
        res.send({
          message: "新增成功",
          failed: false,
        });
      }
    });
  } else {
    db(insetSql, (err, result) => {
      const { insertId } = result;
      if (result.affectedRows === 1) {
        const insetSqlTop = `INSERT INTO article_category (category_name,isTopLevel, parentId,category_count) VALUES ("${childrenValue}", 0, ${insertId},0)`;
        db(insetSqlTop, (err, result) => {
          if (result.affectedRows === 1) {
            res.send({
              message: "新增成功",
            });
          }
        });
      }
    });
  }
});
/**
 * @description: 文章标签删除接口
 * @param {*}
 * @return {*}
 */
article.delete("/article/category/delete", (req, res) => {
  const ids = req.body;
  let deleteSql = `delete from article_category where category_id in (${ids.toString()}) `;
  db(deleteSql, (err, result) => {
    if (result.affectedRows !== 0) {
      res.send({
        failed: false,
        message: "删除成功",
      });
    }
  });
});

module.exports = article;
